package com.systar.activity.report;

import java.nio.ByteBuffer;

public class ActivityData
{
	private String name;
	private Boolean isActive;
	private Integer nbErrors;
	private Integer nbCooledErrors;
	
	public ActivityData(String name)
	{
		this(name, null, null);
	}
	
	public ActivityData(String name, Boolean isActive, Integer nbErrors)
	{
		this.name = name;
		this.isActive = isActive;
		this.nbErrors = nbErrors;
		if (nbErrors != null)
			nbCooledErrors = 0;
	}
	
	public String getName()
	{
		return name;
	}
	
	/* Active management */
	public boolean isActive()
	{
		return (isActive != null) ? isActive : false;
	}
	public void setActive(boolean isActive)
	{
		this.isActive = isActive;
	}
	
	/* Error management */
	public String getErrorMessage()
	{
		if ((nbErrors == null) || (nbErrors == 0))
			return "";
		if ((nbCooledErrors == null) || (nbCooledErrors == 0))
			return String.format(" (%d errors)", nbErrors);
		return String.format(" (%d / %d errors)", nbErrors-nbCooledErrors, nbErrors);
	}
	public void addErrors(int nbErrors)
	{
		if (this.nbErrors == null)
			this.nbErrors = 0;
		if (this.nbCooledErrors == null)
			this.nbCooledErrors = 0;
		
		this.nbErrors += nbErrors;
	}
	public void cooldownErrors()
	{
		nbCooledErrors = nbErrors;
		if (nbCooledErrors == null)
			nbCooledErrors = 0;
	}
	public boolean hasHotErrors()
	{
		if (nbErrors == null)
			return false;
		if (nbCooledErrors == null)
			return (nbErrors > 0);
		return (nbErrors > nbCooledErrors);
	}
	
	public void append(ActivityData other)
	{
		if (other.isActive != null)
			this.isActive = other.isActive;
		if (other.nbErrors != null)
			addErrors( other.nbErrors );
		if ((other.nbCooledErrors != null) && (other.nbErrors == null))
			cooldownErrors();
	}

	public void override(ActivityData other)
	{
		if (other.isActive != null)
			this.isActive = other.isActive;
		if (other.nbErrors != null)
			this.nbErrors = other.nbErrors;
		if ((other.nbCooledErrors != null) && (other.nbErrors == null))
			cooldownErrors();
	}

	public void setData(byte[] zkData)
	{
		ByteBuffer data = ByteBuffer.wrap(zkData);
		isActive = (data.get() != 0);
		nbErrors = data.getInt();
	}
}
